/*
 * Copyright (c) 2012 Johan Fylling
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights 
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

part of engine;


class Percept {
  Actor            _actor;
  WorldState       _worldState;
  CollisionManager _collisionManager;
  
  void init (Actor actor, WorldState worldState, CollisionManager collisionManager) {
    this._actor = actor;
    this._actor.fieldOfView.init(this._actor);
    this._worldState = worldState;
    this._collisionManager = collisionManager;
  }
  
  num get clock => this._worldState.clock;
  
  Vector2 get position => new Vector2.copy(this._actor.body.position);
  
  Vector2 getPosition (int id) {
    if (this._actor.fieldOfView.isSeen(this._collisionManager, id)) {
      WorldObject wo = this._worldState.getObject(id);
      if (wo != null) {
        return wo.body.position;
      }
    }
    return null;
  }
  
  Vector2 get velocity => new Vector2.copy(this._actor.body.velocity);
  
  Vector2 get orientation => new Vector2.fromAngle(this._actor.body.angle, DynamicBody.baseOrientation);
  
  num getNumAttribute (String id) {
    WorldObjectAttribute attribute = this._actor.attributes[id];
    if (attribute != null && attribute is NumWorldObjectAttribute) {
      return attribute.data;
    }
    return null;
  }
  
  void set movementAction (MovementAction action) {
    this._actor.movementAction.clone(action);
  }
  
  void addAction (Action action) {
    this._actor.actions.addLast(action);
  }
  
  ReadOnlyInventory get inventory {
    return this._actor.inventory;
  }
  
  Set<int> get seenActors  {
    Set<int> seenActors = new Set<int>();
    seenActors.addAll(this._actor.fieldOfView.getSeenActors(this._collisionManager));
    return seenActors;
  }
  
  toJson () {
    return {
      "type": "percept"
    };
  }
}


class PerceptStorageHandler {
  call (StorageManager manager, Map attributes) {
    return new Percept();
  }
}
